<template>
  <div class="user">
    <el-row v-if="is_login" justify="center" class="user_login">
      <el-card style="width: 500px; height: auto" v-loading="is_loading">
        <template #header>
          <el-row align="middle" justify="end">
            <el-col span="2">
              <el-button type="primary" text @click="is_login = false" link>
                注册账号
                <el-icon>
                  <ArrowRight />
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
        </template>
        <template #default>
          <el-form ref="login_form" status-icon label-position="right" size="large" label-width="auto"
            :model="loginForm" :rules="rules" style="width: 100%">
            <el-form-item label="账户名" prop="account">
              <el-tooltip effect="dark" content="数字和字母组合 8~12位" placement="right">
                <el-input v-model="loginForm.account" maxlength="12" minlength="8" />
              </el-tooltip>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-tooltip effect="dark" content="大写字母开头 8~10位" placement="right">
                <el-input type="password" v-model="loginForm.password" minlength="8" maxlength="14" />
              </el-tooltip>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <div class="right-flex">
            <el-button type="primary" @click="login_event(login_form)"> 登录 </el-button>
          </div>
        </template>
      </el-card>
    </el-row>
    <el-row v-else justify="center">
      <el-card v-loading="is_loading" style="width: 500px;height: auto">
        <template #header>
          <el-row align="middle" justify="right">
            <el-col span="2">
              <el-button type="primary" link text @click="is_login = true"><el-icon>
                  <ArrowLeft />
                </el-icon>
                登录账号
              </el-button>
            </el-col>
          </el-row>
        </template>
        <template #default>
          <el-form size="large" ref="form" status-icon label-position="right" label-width="auto" :model="userForm"
            :rules="rules">
            <el-form-item label="账户名" prop="account">
              <el-tooltip effect="dark" content="数字和字母组合 8~12位" placement="right">
                <el-input v-model="userForm.account" maxlength="12" minlength="8" />
              </el-tooltip>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-tooltip effect="dark" content="大写字母开头 8~10位" placement="right">
                <el-input type="password" v-model="userForm.password" minlength="8" maxlength="14" />
              </el-tooltip>
            </el-form-item>
            <el-form-item label="用户昵称">
              <el-tooltip effect="dark" content="随意发挥" placement="right">
                <el-input v-model="userForm.name" maxlength="10" />
              </el-tooltip>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <div class="right-flex">
            <el-button type="primary" @click="register(form)"> 注册 </el-button>
          </div>
        </template>
      </el-card>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, toRaw } from "vue";
import { RegRules, post as http_post, URL } from "../../tool/common.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const is_login = ref(true);
const is_loading = ref(false);
const form = ref(); // 获取表单实例
const login_form = ref(); // 获取登录表单实例
const loginForm = ref({
  account: "1258812720",
  password: "Lhb19951027",
});

const userForm = ref({
  name: "蔡徐坤",
  account: "1258812720",
  password: "L19951027",
});


function checked_user(e, val, call) {
  return RegRules(val).Account(false);
}
function checked_pwd(e, val, call) {
  return RegRules(val)?.Password(false);
}
const rules = reactive({
  account: [
    {
      type: "string",
      validator: checked_user,
      required: true,
      message: "请输入正确的账户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      type: "string",
      validator: checked_pwd,
      required: true,
      message: "密码不合法",
      trigger: "blur",
    },
  ],
});
function register(elForm) {
  elForm.validate((p) => {
    if (p) {
      is_loading.value = true;
      const to_raws = toRaw(userForm);
      // 存储数据
      http_post({
        url: URL.BASE + URL.API_USER_SIGN,
        data: {
          param: to_raws.value,
        },
      }).then((res) => {
        let msg;
        let code = res.code;
        if (code === 200) {
          msg = "恭喜，注册成功";
        } else if (code === 300) {
          msg = "账户已存在，请重新输入";
        }
        ElMessage({
          offset: 40,
          duration: 1600,
          type: code === 300 ? "warning" : code === 200 ? "success" : "error",
          message: msg,
          onClose() {
            if (code === 200) {
              ElMessageBox.confirm("是否自动登陆")
                .then(() => {
                  // 获取缓存登陆 要到后端获取令牌才可以
                })
                .catch(() => {
                  void 0; // 什么也不操作
                });
            }
          },
        });
        is_loading.value = false;
      });
    } else {
      ElMessage.error("输入信息有误，请重新输入");
    }
  });
}
// 用户登录事件
function login_event(el = null) {
  el.validate((e) => {
    if (e) {
      is_loading.value = true;
      http_post({
        url: URL.BASE + URL.API_USER_LOGINL,
        data: loginForm.value,
      })
        .then((res) => {
          if (!res || res.code === 500) {
            ElMessage.error({
              message: "服务器异常,请稍后尝试",
            });
            return;
          }
          let code = res.code;
          if (code === 200) {
            Cookies.set("token", res.token);// 写入cookie
            ElMessage.success({
              message: "登录成功",
              duration: 800,
              onClose() {
                router.back();
              },
            });
          } else if (code === 300) {
            ElMessage.error({
              message: "账户登录失败，请检查账号或密码是否正确",
              duration: 3000,
            });
          } else {
            ElMessage.error({
              message: "登录错误",
              duration: 800,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        }).finally(() => is_loading.value = !1);
    } else {
      console.error("表单验证失败");
    }
  });
}
</script>

<style scoped lang="scss">
.user {
  height: auto;
  position: relative;
  top: 20%;

  .right-flex {
    text-align: right;
    width: 100%;
  }

  .user_login {
    box-sizing: border-box;
  }

}
</style>
